package com.lcq.study.test.demo;

import com.lcq.study.test.demo.annotation.AesRequestBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;

/**
 * @ClassName AesEncyptAdvice
 * @Description
 * @Author lichuanqi
 * @Date 2022/9/24 16:10
 * @Version 1.0
 **/
@ControllerAdvice
@Slf4j
public class AesRequestBodyAdvice extends RequestBodyAdviceAdapter {

    @Value("${xk.aes-key}")
    private String aesKey;

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {

        return (AbstractJackson2HttpMessageConverter.class.isAssignableFrom(converterType) &&
                methodParameter.getParameterAnnotation(AesRequestBody.class) != null);
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter methodParameter,
                                           Type targetType, Class<? extends HttpMessageConverter<?>> selectedConverterType) throws IOException {
        RequestMapping mapping = methodParameter.getMethodAnnotation(RequestMapping.class);
        String[] value = mapping.value();
        String url = String.join(",", value);
        log.info("url:{}", url);
        String charset = "UTF-8";
        String body = IOUtils.toString(inputMessage.getBody(), charset);
        String decryptBody = AesUtils.decrypt(body, aesKey);
        InputStream inputStream = IOUtils.toInputStream(decryptBody, charset);
        return new HttpInputMessage() {
            @Override
            public InputStream getBody() throws IOException {
                return inputStream;
            }

            @Override
            public HttpHeaders getHeaders() {
                return inputMessage.getHeaders();
            }
        };
    }




}
